package com.tcc.util.common;


import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private static String SALT = "tcc";


    /**
     * 默认
     *
     * @param password
     * @return
     */
    public static String md5Hash(String password) {
        //开始修饰
        return DigestUtils.md5Hex(password + SALT);
    }

    public static String md5Hash(String password, String salt) {
        //开始修饰
        SALT = salt;
        return DigestUtils.md5Hex(password + SALT);
    }

    /**
     * 文件 加密
     *
     * @param file
     * @return
     */
    public static String getMD5(MultipartFile file) {
        StringBuffer sb = new StringBuffer("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(file.getBytes());
            byte b[] = md.digest();
            int d;
            for (int i = 0; i < b.length; i++) {
                d = b[i];
                if (d < 0) {
                    d = b[i] & 0xff;
                    // 与上一行效果等同
                    // i += 256;
                }
                if (d < 16) {
                    sb.append("0");
                }
                sb.append(Integer.toHexString(d));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


}
